package com.example.eurekac.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.eurekac.test;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: config-client
 * @description: 访问微信第三方服务器获取session_key
 * @author: ZhouGuoFeng
 * @create: 2018-12-12 16:32
 **/
    public class WeChatUtil {
        public static String session_key="";
        //访问接口
        public static Map<String,String> getURLContent(String appId, String code, String appSecret) throws Exception {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code);
            HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("GET");
            //设置请求属性
//            httpConn.setRequestProperty("accept", "*/*");
//            httpConn.setRequestProperty("token", test.token);
            httpConn.setRequestProperty("connection", "Keep-Alive");
            httpConn.setRequestProperty("content-type", "application/json; charset=utf-8");
            httpConn.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            httpConn.disconnect();
            System.out.println(buffer.toString());
            JSONObject jsonp = JSON.parseObject(buffer.toString());
            String openID=jsonp.getString("openid");//openID
            String sessionkey=jsonp.getString("session_key");// sessionkey
            Map<String,String> map=new HashMap<>();
            map.put("openID",openID);
            map.put("sessionkey",sessionkey);
            session_key=sessionkey;
            return map;
        }
}
